package com.example.weatherdemo.server;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.concurrent.TimeUnit;

/**
 * @author junoppa
 */
public class WeatherDataCache {
    private Cache<String,String> cache = CacheBuilder.newBuilder()
            .recordStats()
            .maximumSize(5000000)
            .expireAfterWrite(1, TimeUnit.MINUTES)
            .build();

    public  String getCityWeather(String city) throws Exception {
        String value = cache.getIfPresent(city);
        //缓存不存在
        if(value==null || value ==""){
            String url = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
            OkHttpClient okHttpClient = new OkHttpClient();
            final Request request = new Request.Builder()
                    .url(url)
                    .build();
            final Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            value =  response.body().string();
            cache.put(city,value);
        }
        System.out.println("查询天气数据：" + value);
        return value;
    }

    public static void main(String[] args) throws Exception{
        WeatherDataCache cache = new WeatherDataCache();
        long startTime = System.currentTimeMillis();
        for (int i=0;i<50;i++){
            cache.getCityWeather("北京");
        }
        for (int i=0;i<40;i++){
            cache.getCityWeather("上海");
        }
        for (int i=0;i<30;i++){
            cache.getCityWeather("广州");
        }
        for (int i=0;i<20;i++){
            cache.getCityWeather("深圳");
        }
        for (int i=0;i<10;i++){
            cache.getCityWeather("南京");
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("----costTime: "+(endTime2 - startTime) +" 毫秒");
    }

}
